package com.nlx.notes.module.service.impl.flow;

import com.google.common.eventbus.Subscribe;
import com.nlx.notes.module.bean.bo.FlowMonthAmountStatisticsBO;
import com.nlx.notes.module.bean.dto.flow.FlowChangeDTO;
import com.nlx.notes.module.core.consts.GlobalConst;
import com.nlx.notes.module.core.util.DateUtils;
import com.nlx.notes.module.entity.FlowDayStatistics;
import com.nlx.notes.module.entity.FlowMonthStatistics;
import com.nlx.notes.module.service.IFlowDayStatisticsService;
import com.nlx.notes.module.service.ITransactionsService;
import com.nlx.notes.module.service.flow.FlowStatisticsManageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;

@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class FlowDayStatisticsManageServiceImpl implements FlowStatisticsManageService {

    private static final String STATISTICS_TYPE = "day";


    final IFlowDayStatisticsService flowDayStatisticsService;

    final ITransactionsService transactionsService;

    @Override
    public String getType() {
        return STATISTICS_TYPE;
    }

    @Subscribe
    @Override
    public void flowChange(FlowChangeDTO flowChangeDTO) {
        log.info("月统计被触发了、、、、");
        this.updateDayAmount(flowChangeDTO.getUserId(),flowChangeDTO.getFlowNewDate(),flowChangeDTO.getBookId());
        this.updateDayAmount(flowChangeDTO.getUserId(),flowChangeDTO.getFlowOldDate(),flowChangeDTO.getBookId());
    }

    private void updateDayAmount(Long userId, LocalDate flowNewDate, Long bookId) {
        if(null == flowNewDate){
            return ;
        }
        String dayDate = DateUtils.formatDate(flowNewDate);
        FlowMonthAmountStatisticsBO flowMonthAmountStatisticsBO = transactionsService.sumByDate(dayDate,dayDate, userId,bookId);
        FlowDayStatistics flowDayStatistics = flowDayStatisticsService.findByDay(dayDate, userId,bookId);
        if(null == flowDayStatistics){
           flowDayStatistics = new FlowDayStatistics();
           flowDayStatistics.setExpense(flowMonthAmountStatisticsBO.getExpenseAmount());
           flowDayStatistics.setIncome(flowMonthAmountStatisticsBO.getIncomeAmount());
           flowDayStatistics.setDayTime(dayDate);
            flowDayStatistics.setBookId(bookId);
           flowDayStatistics.setUserId(userId);
           flowDayStatistics.setDelFlag(GlobalConst.DEL_FLAG_NORMAL);
        }else{
            flowDayStatistics.setExpense(flowMonthAmountStatisticsBO.getExpenseAmount());
            flowDayStatistics.setIncome(flowMonthAmountStatisticsBO.getIncomeAmount());
        }
        flowDayStatisticsService.saveOrUpdate(flowDayStatistics);
    }
}
